#!/bin/bash
# Copyright (c) 2007, Commerce360, Inc.
# 
# All rights reserved.
# 
# Redistribution and use in source and binary forms, with or without 
# modification, are permitted provided that the following conditions 
# are met:
# 
#     * Redistributions of source code must retain the above copyright 
#       notice, this list of conditions and the following disclaimer.
#     * Redistributions in binary form must reproduce the above copyright 
#       notice, this list of conditions and the following disclaimer in 
#       the documentation and/or other materials provided with the 
#       distribution.
#     * Neither the name of the Commerce360, Inc. nor the names of its 
#       contributors may be used to endorse or promote products derived 
#       from this software without specific prior written permission.
# 
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 
# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, 
# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT 
# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, 
# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY 
# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 
# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE 
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
# 

#
# Script to run at startup and shutdown to register/deregister this EC2
# instance's public IP address with the Nettica DNS service
#
OUROPTION="netticaupdate"
NETTICAOPTIONS=""
INSTANCEDATA=`curl -s -f http://169.254.169.254/latest/user-data`
[ "$?" != "0" ] && echo "error: could not retrieve instance data" >&2 && exit 1
PUBLICIP=`curl -s -f http://169.254.169.254/latest/meta-data/public-ipv4`
[ "$?" != "0" ] && echo "error: could not retrieve public IPv4 address" >&2 && exit 1

do_update() {
    COMMAND=$1
    java -jar /usr/bin/netticadns.jar \
	-c $COMMAND \
	-i $PUBLICIP \
	$NETTICAOPTIONS
    if [ "$?" != "0" ]; then
	echo "error: could not add to Nettica DNS service this instance's IP" >&2
	exit 1
    fi
}

check_update() {
    X=`echo $INSTANCEDATA | /usr/bin/extract_ec2_option $OUROPTION`
    [ "$X" = "" ] && echo "no update for this instance" && exit 0
    NETTICAOPTIONS="$NETTICAOPTIONS $X"
}

check_update
case "$1" in
    start)
	do_update add
	;;
    stop)
	do_update delete
	;;
    *)
	echo "usage: $0 {start|stop}" >&2
	exit 1
	;;
esac
